#ifdef WIN
    #include <Ws2tcpip.h>
#else
#endif
#include "client.h"
#include <stdio.h>
#include <string.h>


struct atm_msg balance(struct atm_msg msg){
    int success = -1,bytes_sent = -1, msg_len = -1;
    struct atm_msg msg_recv;
    
    msg_len = sizeof(msg);
    
    bytes_sent = send(activesocket,(void *)&msg,msg_len,NO_FLAG);
    if(bytes_sent < msg_len){
    	fprintf(stderr,"Error Client sending packet, whole message not sent\n");
    } 
    recv(activesocket, (void*)&msg_recv, sizeof(msg_recv),NO_FLAG);
        
    return msg_recv;
}

struct atm_msg deposit(struct atm_msg msg){
    int success = -1,bytes_sent = -1, msg_len = -1;
    struct atm_msg msg_recv;
    
    msg_len = sizeof(msg);
    
    bytes_sent = send(activesocket,(void *)&msg,msg_len,NO_FLAG);
    if(bytes_sent < msg_len){
    	fprintf(stderr,"Error Client sending packet, whole message not sent\n");
    }
     
    recv(activesocket, (void*)&msg_recv, sizeof(msg_recv),NO_FLAG);
        
    return msg_recv;
}

struct atm_msg withdraw(struct atm_msg msg){
    int success = -1,bytes_sent = -1, msg_len = -1;
    struct atm_msg msg_recv;
    
    msg_len = sizeof(msg);
    
    bytes_sent = send(activesocket,(void *)&msg,msg_len,NO_FLAG);
    if(bytes_sent < msg_len){
    	fprintf(stderr,"Error Client sending packet, whole message not sent\n");
    }
     
    recv(activesocket, (void*)&msg_recv, sizeof(msg_recv),NO_FLAG);
        
    return msg_recv;
}

/** Establishes a connections */
int connectClient(const char* server_address){
    //int activesocket;
    int success = -1;
    struct sockaddr_in remoteAddr, localAddr;
    struct hostent *hptr;

    activesocket = socket(AF_INET, SOCK_STREAM, 0);
    remoteAddr.sin_family = AF_INET; 
    remoteAddr.sin_port=htons(MYPORT);
    hptr = gethostbyname( server_address );

    memcpy((char*)&remoteAddr.sin_addr.s_addr,
            hptr->h_addr_list[0], hptr->h_length);

    success = connect(activesocket, (struct sockaddr *)&remoteAddr, sizeof(struct sockaddr));
    if(success <0){
        fprintf(stderr,"Error connecting to client\n"); 
        return -1;
    }

    return 0;
}

int disconnectClient(){
    close(activesocket);
}


